/**
 * 
 */
package cn.aidee.process;

import java.util.logging.Level;

import org.compiere.model.MPayment;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.AdempiereUserError;
import cn.aidee.model.MCBilling;

/**
 * @author v-alyang
 *
 */
public class CreateLineFromBilling extends SvrProcess
{

	/** The Record						*/
	private int		p_C_Payment_ID = 0;
	/**	Billing ID				*/
	private int		p_C_Billing_ID = 0;
	
	/**
	 *  Prepare - e.g., get Parameters.
	 */
	protected void prepare()
	{
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++)
		{
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;		
			if (name.equals("C_Billing_ID"))
				p_C_Billing_ID = para[i].getParameterAsInt();
			else
				log.log(Level.SEVERE, "Unknown Parameter: " + name);
		}
		p_C_Payment_ID = getRecord_ID();
	}	//	prepare

	/**
	 * 	Process
	 *	@return message
	 *	@throws Exception
	 */
	protected String doIt() throws Exception
	{
		int cnt = 0;
		
		log.info("C_Payment_ID=" + p_C_Payment_ID + ", C_Billing_ID=" + p_C_Billing_ID);
		
		MPayment pay = new MPayment (getCtx(), p_C_Payment_ID, get_TrxName());
		if (pay.get_ID() == 0)
			throw new IllegalArgumentException("Not found C_Payment_ID=" + p_C_Payment_ID);
				
		MCBilling bil = new MCBilling(getCtx(), p_C_Billing_ID, get_TrxName());
		if (bil.getC_Billing_ID() == 0)
			throw new AdempiereUserError("@No@ @Billing@");

		cnt = bil.createLineFromBilling(pay);
		
		if (cnt == -1)
			throw new AdempiereUserError("Error creating payment line from billing, please check log");

		return "@Inserted@=" + cnt;
	}	//	doIt

}
